package demo1230.lianxi;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
创建服务端对象:

 */
public class ServerSocket_01 {
    public static void main(String[] args) {
//        创建服务器端的对象   ip:  192.168.43.36  9999
        try (ServerSocket ss = new ServerSocket(9999)) {
            while (true) {
//            接收客户端对象
                Socket accept = ss.accept();
                new Thread(() -> {
                    try {
//            获取网络字节输入流对象
                        InputStream is = accept.getInputStream();
//            创建本地的字节输出流对象,把读取到的图片写出
                        String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                        FileOutputStream fos = new FileOutputStream("server\\" + name + ".jpg");
//            读取数据
                        int read;
                        byte[] bs = new byte[1024];

                        while ((read = is.read(bs)) != -1) {
                            fos.write(bs, 0, read);
                        }

//            回写一个收到了
//            获取网络字节输出流对象
                        OutputStream os = accept.getOutputStream();
                        os.write("收到了".getBytes());
//            结束标志
                        accept.shutdownOutput();
//            关闭资源
                        fos.close();
                        accept.close();

                    } catch (Exception e) {
                        System.out.println(e);
                    }

                }).start();


            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
